package me.minecraft.mod.resourcepackdemo.mixin;

import net.minecraft.resource.LifecycledResourceManagerImpl;
import net.minecraft.resource.NamespaceResourceManager;
import net.minecraft.resource.Resource;
import net.minecraft.resource.ResourceManager;
import net.minecraft.util.Identifier;
import org.slf4j.Logger;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;

import java.util.Map;
import java.util.Optional;

/**
 * @author langle__
 * @version 1.0
 */
@Mixin(LifecycledResourceManagerImpl.class)
public class LifecycledResourceManagerImplMixin {

    @Shadow @Final private static Logger LOGGER;

    @Shadow @Final private Map<String, NamespaceResourceManager> subManagers;

    @Inject(method = "getResource", at = @At("HEAD"), cancellable = true)
    private void getResource(Identifier identifier, CallbackInfoReturnable<Optional<Resource>> cir) {
        cir.cancel();
        ResourceManager resourceManager = this.subManagers.get(identifier.getNamespace());
        if (resourceManager == null) {
            cir.setReturnValue(Optional.empty());
            return;
        }
        Optional<Resource> resource = resourceManager.getResource(identifier);
        if (resource.isEmpty()) {
            Identifier ide = Identifier.tryParse(identifier.getNamespace(), identifier.getPath() + "\\");
            resource = resourceManager.getResource(ide);
        }
        cir.setReturnValue(resource);
    }

}
